package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Service
@Transactional
@Slf4j
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<Address> findList() {
        //1. 设置查询条件
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());

        //2. 执行查询
        return addressMapper.selectList(wrapper);
    }

    @Override
    public void save(Address address) {
        log.info("即将保存的地址信息为:{}", address);

        //设置UserId
        address.setUserId(UserHolder.get().getId());

        //保存
        addressMapper.insert(address);
    }

    @Override
    public void updateDefault(Long id) {
        //1. 修改当前用户的所有地址的is_default=0
        //update address set is_default=0 where user_id=登录用户id
        //1-1 封装要更新的字段
        Address address1 = new Address();
        address1.setIsDefault(0);

        //1-2 设置更新条件
        LambdaUpdateWrapper<Address> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());

        //1-3 执行更新
        //参数一: 要更新的字段,  参数二: 根据什么条件更新
        addressMapper.update(address1, wrapper);


        //2. 将指定id记录的is_default=1
        //update address set is_default=1 where id = ?
        Address address2 = new Address();
        address2.setId(id);
        address2.setIsDefault(1);
        addressMapper.updateById(address2);
        //findDefault();
    }

    @Override
    public Address findDefault() {
        //select * from address where user_id = ? and is_default = 1
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        wrapper.eq(Address::getIsDefault, 1);

        return addressMapper.selectOne(wrapper);

    }

    @Override
    public Address findById(Long id) {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getId, id);
        return addressMapper.selectById(id);

    }

    @Override
    public void updateById(Address address) {
        addressMapper.updateById(address);
    }

    @Override
    public void deleteById(Long ids) {
        addressMapper.deleteById(ids);
    }

}